package org.hy.dao.impl;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.hy.dao.StaffDao;
import org.hy.entity.Staff;
import org.hy.util.DruidUtil;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class StaffDaoimpl4DbUtils implements StaffDao {
    QueryRunner qr = new QueryRunner(DruidUtil.getDataSource());
    @Override
    public int insert(Staff staff) {
        String sql = "insert into staffs(name,age,phone,sta_pos) values(?,?,?,?)";

        Object[] params = {staff.getName(),staff.getAge(),staff.getPhone(),staff.getStaPos()};

        try {
            return qr.update(sql,params);
        } catch (SQLException e) {
            throw new RuntimeException("添加失败",e);
        }
    }

    @Override
    public int delete(int id) {
        String sql = "delete from staffs where id = ?";
        Connection conn = null;
        try {
            conn = DruidUtil.getConnection();
            return qr.update(conn,sql,id);
        } catch (SQLException e) {
            throw new RuntimeException("删除失败",e);
        }
    }

    @Override
    public int updateUser(Staff staff) {
        String sql = "update staffs set name = ?,age = ?,phone = ?,sta_pos = ?,update_time = ? where id = ?";
        Object[] params = {staff.getName(),staff.getAge(),staff.getPhone(),staff.getStaPos(),staff.getUpdateTime(),staff.getId()};
        try {
            return qr.update(sql,params);
        } catch (SQLException e) {
            throw new RuntimeException("修改失败",e);
        }
    }

    @Override
    public List<Staff> selectByPage(int currentPage, int pageSize) {
        String sql = "select " +
                "id,name,age,phone,sta_pos as staPos,add_time as addTime,update_time as updateTime " +
                "from staffs limit ?,?";
        int limit = (currentPage-1) * pageSize;
        BeanListHandler<Staff> beanListHandler = new BeanListHandler<>(Staff.class);

        try {
            return qr.query(sql,beanListHandler,limit,pageSize);
        } catch (SQLException e) {
            throw new RuntimeException("查询失败",e);
        }
    }

    @Override
    public Staff selectById(int id) {
        String sql = "select" +
                " id,name,age,phone,sta_pos as staPos,add_time as addTime,update_time as updateTime " +
                "from staffs where id = ?";
        BeanListHandler<Staff> beanListHandler = new BeanListHandler<>(Staff.class);
        try {
            List<Staff> list = qr.query(sql,beanListHandler,id);
            return list.size() > 0 ? list.get(0) : null;
        } catch (SQLException e) {
            throw new RuntimeException("查询失败",e);
        }
    }
}
